package com.dbapp.shopping.controller;

import com.dbapp.shopping.domain.Good;
import com.dbapp.shopping.domain.User;
import com.dbapp.shopping.service.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.List;

@Controller
@RequestMapping
public class QueryController {

    private Service service;

    @Autowired
    public QueryController(Service service) {
        this.service = service;
    }

    @PostMapping("/search")
    public String homepage(Model model, Principal principal, String query) {
        Authentication authentication = (Authentication) principal;
        if (principal != null && authentication.isAuthenticated()) {
            model.addAttribute("status", true);
            model.addAttribute("user", (User) authentication.getPrincipal());
        } else {
            model.addAttribute("status", false);
        }

        //查找LIKE %query%
        List<Good> res = service.searchGoods(query);
        model.addAttribute("goods", res);

        return "home";
    }
}
